<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
       :disabled="userState"
        placeholder="用户编号"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="queryBtn"
        v-model="queryParams.openid"
      />
      <el-input
       :disabled="userState"
        placeholder="手机号"
        style="width: 200px; margin-left: 10px"

        class="filter-item"
        @keyup.enter.native="queryBtn"
        v-model="queryParams.remark"
      />
      <!-- <el-input
        v-model="queryParams.remark"
        placeholder="电话号码"
        clearable
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      /> -->
      <!-- <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select> -->
      <!-- <el-select
        v-model="listQuery.number"
        placeholder="数字"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item.key"
          :label="item.display_name + '(' + item.key + ')'"
          :value="item.key"
        />
      </el-select> -->

      <el-button
      :disabled="userState"
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 5px;"
        @click="queryBtn"
      >
        查询
      </el-button>
      <!-- <el-button
      :disabled="userState"
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button> -->

      <span style="float: right;
    margin-right: 20px;
    font-weight: 600;color: #494949;">当前账号：<span style="color: #ff770f;">{{title}}</span></span>
  

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{ background: '#ffffff', color: '#000000' }"
      :data="list"
      :row-class-name="tableRowClassName"
      border
      fit
      highlight-current-row
      style="
        width: 100%;
        font-size: 15px;
        box-shadow: 1px 1px 8px #cdcdcd;
        border: 0px;
      "
      @sort-change="sortChange"
    >
      <!-- <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="用户编号" min-width="300px">
        <template slot-scope="{ row }">
          <span>{{ row.openid }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户名称" min-width="250px">
        <template slot-scope="{ row }">
          <span>{{ row.nickname }}</span>
        </template>
      </el-table-column>

      <el-table-column label="电话号码" min-width="120px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.remark }}</span>
        </template>
     </el-table-column>
      <!--  <el-table-column label="充电次数" min-width="250px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.chargeNum }}</span>
        </template>
      </el-table-column>

      <el-table-column label="累计电量" min-width="250px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.elecTotal }}</span>
        </template>
      </el-table-column>

      <el-table-column label="累计费用" min-width="250px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.feeTotal }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="充值余额" width="170px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updateDate }}</span>
        </template>
      </el-table-column> -->

      <el-table-column
        label="操作"
        align="center"
        width="230"
        fixed="true"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    /> -->

    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination
          layout="total,sizes,prev, pager,next,jumper"
          style="margin-top: 10px;"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="handlePageChange"
          @current-change="handleNoChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-select
            v-model="temp.phone"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间" prop="createDate">
          <el-date-picker
            v-model="temp.createDate"
            type="datetime"
            placeholder="Please pick a date"
          />
        </el-form-item>

        <el-form-item label="数字">
          <el-select
            v-model="temp.number"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="Remark">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >Confirm</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>


<style>
.el-table .warning-row {
  background: #fff5ee;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #fdc091;
}
.el-table__body tr.current-row > td {
  background-color: #fdc091;
}
</style>

<script>
// import { listCustomer, exportCustomer } from "@/api/customer";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import axios from "axios";
import { getToken } from "@/utils/auth";
import { loadcustomerApi } from "@/api/car";
import { getNickName, getTestUserName } from "../../utils/auth";

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      queryParams: {
        openid: "",
        remark: "",
        key:""
      },
      tableKey: 0,
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name: undefined,
        phone: undefined,
        number: undefined,
        sort: "+id",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      searchVal: "",
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      key:"",
      title:"",
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },
  created() {
    //  this.getList()
  },
  mounted: function () {
    this.key = localStorage.getItem("key");
    this.queryParams.key = localStorage.getItem("key");
    this.title = localStorage.getItem("title");
    // this.$nextTick(function () {
    //   this.loadcustomer(this.pageNo, this.pageSize);
    // });
  },
  computed: {

    userState () {
      return getNickName() === getTestUserName();
    }
    // list() {
    //   return this.list.filter((item) => item.includes(this.listQuery.openid));
    // },
  },
  methods: {
    //   loadcustomerProcs (pageNo, pageSize) {
    //   let _this = this;
    //   _this.loading = true;
    //   loadInvoiceProcApi({ pageNo: pageNo, pageSize: pageSize, openid: _this.queryParams.openid, nickname: _this.queryParams.nickname})
    //     .then(resp => {
    //       _this.invoiceProcs = resp.data.dataList;
    //       _this.total = resp.data.totalNum;
    //       _this.loading = false;
    //     })
    //     .catch(e => {
    //       this.loaded = false;
    //       this.loading = false;
    //       console.log(e);
    //     });
    // },

    queryBtn() {
      let _this = this;
      _this.loading = true;
      console.log("_this.form: {}", _this.form);
      this.loadcustomer(_this.pageNo, _this.pageSize);
    },

    // getList() {
    //   this.listLoading = true;
    //   listCustomer(this.listQuery).then((response) => {
    //     this.list = response.data.list;
    //     this.total = response.data.total;

    //     // Just to simulate the time of the request
    //     setTimeout(() => {
    //       this.listLoading = false;
    //     }, 1.5 * 1000);
    //   });
    // },

    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 0) {
        return "warning-row";
      }
      return "";
    },
    //列表页码的触发事件
    handlePageChange(pageSize) {
      this.pageSize = pageSize;
      this.loadcustomer(this.pageNo, this.pageSize);
    },
    handleNoChange(pageNo) {
      this.pageNo = pageNo;
      this.loadcustomer(this.pageNo, this.pageSize);
    },
    loadcustomer(pageNo, pageSize) {
      let _this = this;
      _this.listLoading = true;
      loadcustomerApi({ pageNo: pageNo, pageSize: pageSize, openid: _this.queryParams.openid, remark: _this.queryParams.remark,roleCode:_this.key }).then(
        (response) => {
          _this.list = response.data.dataList;
          _this.total = response.data.totalNum;
          setTimeout(() => {
            _this.listLoading = false;
          }, 1 * 1000);
        }
      );
    },
    //////////////////////////

    handleFilter() {
      this.listQuery.pageNo = 1;
   //   this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success",
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addCar(this.temp).then(() => {
       //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateCar(this.temp).then(() => {
     //       this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteCar({ id: row.id }).then(() => {
    //      this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "Success",
            message: "Delete Successfully",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      axios({
        method: "GET",
        url: "/vehicleMap/lcuser/exportUsersByroleCode",
        params: this.queryParams,
        headers: { pacargle: getToken() },
        responseType: "blob", //返回是个文件
      }).then((response) => {
        this.download(response); //then直接下载，方法在下边
      });
    },
    download(res) {
      let blob = new Blob([res.data], { type: "text/xls,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob);
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute(
        "download",
        decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1]
        )
      );
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>
